package com.distribution.system.controller;

import com.distribution.common.annotation.RepeatSubmit;
import com.distribution.common.core.controller.BaseController;
import com.distribution.common.core.domain.AjaxResult;
import com.distribution.common.core.domain.entity.SysUser;
import com.distribution.common.core.page.TableDataInfo;
import com.distribution.common.utils.poi.ExcelUtil;
import com.distribution.system.domain.bo.AgentListExportBo;
import com.distribution.system.domain.dto.AgentAddDto;
import com.distribution.system.domain.dto.AgentDTO;
import com.distribution.system.domain.req.ChangeSupAgentReq;
import com.distribution.system.domain.req.MergeAgentToReq;
import com.distribution.system.mapper.SysUserMapper;
import com.distribution.system.service.AgentManageService;
import com.distribution.system.service.ISysUserService;
import com.distribution.system.utils.convert.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * @author niejiandeng
 * @date 2023年05月21日 15:20
 */
@RestController
@RequestMapping(value = "/agentManage")
@Slf4j
@Validated
public class AgentManageController extends BaseController {
    @Resource
    AgentManageService agentManageService;
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    private ISysUserService userService;

    /**
     * 新增代理
     */
    @PostMapping("/addAgent")
    @RepeatSubmit()
    public AjaxResult addAgent(@RequestBody @Valid AgentAddDto agentAddDto) {
        agentManageService.addAgent(agentAddDto);
        return success();
    }

    /**
     * 停用代理
     */
    @PostMapping("/banAgentByUserId")
    @RepeatSubmit()
    public AjaxResult banAgentByUserId(@RequestBody Long userId) {
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        sysUser.setStatus("1");
        userService.updateUser(sysUser);
        return success();
    }

    /**
     * 启用代理
     */
    @PostMapping("/unlockAgentByUserId")
    @RepeatSubmit()
    public AjaxResult unlockAgentByUserId(@RequestBody Long userId) {
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        sysUser.setStatus("0");
        userService.updateUser(sysUser);
        return success();
    }

    /**
     * 删除代理
     */
    @PostMapping("/delAgentByUserId")
    @RepeatSubmit()
    public AjaxResult delAgentByUserId(@RequestBody Long userId) {
        agentManageService.delAgentByUserId(userId);
        return success();
    }

    /**
     * 修改
     */
    @PostMapping("/updateAgent")
    public AjaxResult updateAgent(@RequestBody AgentDTO agentDTO) {
        //System.out.println("agentDTO = " + agentDTO);
        agentManageService.updateAgent(agentDTO);
        return success();
    }

    /**
     * 设置下级佣金百分比
     * @param subDeduct 百分比
     */
    @PostMapping("/setSubDeduct/{subDeduct}")
    public AjaxResult setSubDeductPercent(@PathVariable Double subDeduct) {
//        System.out.println("subDeduct = " + subDeduct);
        agentManageService.setSubDeduct(subDeduct);
        return success();
    }

    /**
     * @Author: GodLu
     * @Date: 2024/5/16 11:49
     * @Description: 查询当前用户的下级抽成
     * @return: Float
     */
    @GetMapping("/getSubDeduct")
    public AjaxResult getSubDeduct() {
        Long userId = getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        return success(sysUser.getSubDeduct());
    }

    /**
     * 查询代理列表
     */
    @PostMapping("/selectAgent")
    public TableDataInfo selectAgent(@RequestBody AgentDTO agentDTO) {
        Long userId = getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);
//        startPage();
        List<SysUser> sysUsers = agentManageService.selectAgent(agentDTO, sysUser);
        return getDataTable(sysUsers);
    }

    /**
     * 查询代理列表
     */
    @PostMapping("/getMyInfo/{userId}")
    public AjaxResult getMyInfo(@PathVariable Long userId) {
        SysUser sysUser = agentManageService.getMyInfo(userId);
        return success(sysUser);
    }

    /**
     * 修改上级代理
     */
    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    @PostMapping("/changeSupAgent")
    public AjaxResult changeSupAgent(@RequestBody ChangeSupAgentReq changeSupAgentReq) {
        SysUser agent = sysUserMapper.selectUserById(changeSupAgentReq.getUserId());
        if (agent == null) return error("用户不存在");
        SysUser supAgent = sysUserMapper.selectUserById(changeSupAgentReq.getSupUserId());
        if (supAgent.isAgentOperation()){
            agent.setRoleId(100L);
        }else if (supAgent.getRoleId() == 100L){
            agent.setRoleId(101L);
        }else if (supAgent.getRoleId() == 101L){
            agent.setRoleId(102L);
        }
        agent.setParentId(changeSupAgentReq.getSupUserId());
        int i = sysUserMapper.updateUser(agent);
        return i > 0 ? success() : error();
    }

    /**
     * 修改上级代理
     */
    @PreAuthorize("@ss.hasPermi('system:agent:merge')")
    @PostMapping("/mergeAgentTo")
    public AjaxResult mergeAgentTo(@RequestBody MergeAgentToReq mergeAgentToReq) {
        AgentDTO agentDTO = new AgentDTO();
        agentDTO.setParentId(mergeAgentToReq.getSourceUserId());
//        List<SysUser> sysUserList = sysUserMapper.selectUserListByParentId(agentDTO);
        List<SysUser> sysUserList = userService.selectUserListByParentId(agentDTO);
        if (sysUserList.isEmpty()) return error("当前用户没有下级代理");
        sysUserList.forEach(f -> {
            if (f.getRoleId() == 100L) {
                f.setParentId(mergeAgentToReq.getTargetUserId());
                sysUserMapper.updateUser(f);
            }
        });
        return success();
    }

    /**
     * 通过代理账号获取代理信息
     */
    @PostMapping("/getAgentInfoByAccount")
    public AjaxResult getAgentInfoByAccount(@RequestBody String account) {
        SysUser sysUser = sysUserMapper.selectUserByUserName(account);
        return sysUser == null ? error("代理账号不存在！") : success(sysUser);
    }

    /**
     * 解绑微信
     */
    @PostMapping("/unbindWeChat")
    public AjaxResult unbindWeChat(@RequestBody SysUser sysUser) {
        agentManageService.unbindWeChat(sysUser);
        return success();
    }

    @PostMapping("/getUserInfoById")
    public AjaxResult getUserInfoById(@RequestBody Long userId){
        //获取当前登录用户
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        return success(sysUser);
    }

    @PostMapping("/export")
    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    public void export(HttpServletResponse response, AgentDTO agentDTO) {
        Long userId = getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        List<SysUser> agentList = agentManageService.selectAgent(agentDTO, sysUser);
        List<AgentListExportBo> agentListExportBos = BeanUtils.copyBeanCollection(AgentListExportBo.class, agentList);
        ExcelUtil<AgentListExportBo> util = new ExcelUtil<>(AgentListExportBo.class);
        util.exportExcel(response, agentListExportBos, "代理数据");
    }
}


